package com.abc.xxx.controller;

import com.abc.xxx.model.User;
import com.abc.xxx.service.UserService;
import com.abc.xxx.util.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * 用户管理
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {

    private static final String NO_AUTH = "权限不足：只有超级管理员才能";

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping
    public Result findUsers(@AuthenticationPrincipal User loginUser,
                            @RequestParam(value = "key", required = false) String key) {
        String oper = "查询用户列表";
        log.info("====>{}, key: {}", oper, key);
        // 权限检查
        if (loginUser.isNotRoot()) {
            log.warn(NO_AUTH + oper);
            return Result.error(oper).msg(NO_AUTH + oper);
        }

        List<User> list = userService.findUsers(loginUser.getId(), key);
        return Result.success(oper).list(list);
    }

    @PostMapping
    public Result addUser(@AuthenticationPrincipal User loginUser,
                          @RequestBody String body) {
        String oper = "新增账号";
        log.info("====>{}, body: {}", oper, body);

        // 只有超级管理员才能新增账号
        if (loginUser.isNotRoot()) {
            log.warn(NO_AUTH + oper);
            return Result.error(oper).msg(NO_AUTH + oper);
        }

        // 数据校正 & 权限判断
        User data = JSON.parseObject(body, User.class);
        data.setCreatorId(loginUser.getId());
        data.setCreated(LocalDateTime.now());

        // 数据校验
        if (isBlank(data.getName())) {
            return Result.error(oper).msg("账号名称不能为空");
        }
        if (isBlank(data.getPwd())) {
            return Result.error(oper).msg("初始密码不能为空");
        }
        if (data.getDeptId() == null) {
            return Result.error(oper).msg("必须分配一个部门");
        }
        if (userService.isAccountExists(data.getName())) {
            return Result.error(oper).msg("账号已存在");
        }
        if (data.getRoot() == null) {
            return Result.error(oper).msg("设置的“是否超级管理员”一项不能为空");
        }
        if (data.root()) {
            // 设置成超级管理员就不需要角色
            data.setRoleId(0);
        }else{
            // 设置成不是超级管理员则一定要设置角色
            if (data.getRoleId() == null) {
                return Result.error(oper).msg("设置的“角色”一项不能为空");
            }
        }

        // 保存数据
        data.setPwd(passwordEncoder.encode(data.getPwd()));
        data.setUpdated(data.getCreated());
        userService.save(data);
        return Result.success(oper)
                .data("id", data.getId())
                .data("time", data.getCreated());
    }

    @DeleteMapping("/{userId}")
    public Result deleteUser(@AuthenticationPrincipal User loginUser,
                             @PathVariable("userId") Integer userId) {
        String oper = "删除用户";
        log.info("====>{}, userId: {}", oper, userId);

        // 权限检查
        if (loginUser.isNotRoot()) {
            log.warn(NO_AUTH + oper);
            return Result.error(oper).msg(NO_AUTH + oper);
        }

        // 数据校验
        if (userId == null) {
            return Result.error(oper).msg("用户id不能为空");
        }
        if (userId.equals(loginUser.getId())) {
            return Result.error(oper).msg("您不能删除自己的账号");
        }

        // 删除数据
        userService.removeById(userId);
        return Result.success(oper);
    }

    /**
     * 场景：超级管理员更新用户账号设置
     *
     * @param loginUser
     * @param userId
     * @param body
     * @return
     */
    @PatchMapping("/{userId}/setting")
    public Result updateUserSetting(@AuthenticationPrincipal User loginUser,
                                    @PathVariable("userId") Integer userId,
                                    @RequestBody String body) {
        String oper = "更新用户账号设置";
        log.info("====>{}, accountId: {}, body: {}", oper, userId, body);

        // 权限检查
        if (loginUser.isNotRoot()) {
            log.warn(NO_AUTH + oper);
            return Result.error(oper).msg(NO_AUTH + oper);
        }

        // 数据校验
        User user = JSON.parseObject(body, User.class);
        if (user.getId() == null) {
            return Result.error(oper).msg("账号id不能为空");
        }
        if (isBlank(user.getName())) {
            return Result.error(oper).msg("设置的“账号名称”一项不能为空");
        }
        if (userService.isUserNameDuplicate(user.getId(),user.getName())) {
            return Result.error(oper).msg("设置的新账号名称已存在");
        }
        if (user.getDeptId() == null) {
            return Result.error(oper).msg("设置的“部门”一项不能为空");
        }
        if (user.getRoot() == null) {
            return Result.error(oper).msg("设置的“是否超级管理员”一项不能为空");
        }
        if (user.root()) {
            // 设置成超级管理员就不需要角色
            user.setRoleId(0);
        }else{
            // 设置成不是超级管理员则一定要设置角色
            if (user.getRoleId() == null) {
                return Result.error(oper).msg("设置的“角色”一项不能为空");
            }
        }

        // 更新数据
        User data = new User();
        data.setId(user.getId());
        data.setName(user.getName());
        data.setRoot(user.getRoot());
        data.setDeptId(user.getDeptId());
        data.setRoleId(user.getRoleId());
        data.setUpdated(LocalDateTime.now());
        userService.updateById(user);
        return Result.success(oper).data("time", data.getUpdated());
    }

    /**
     * 场景：用户更新自己的信息
     *
     * @param loginUser
     * @param userId
     * @param body
     * @return
     */
    @PatchMapping("/my-info")
    public Result updateMyInfo(@AuthenticationPrincipal User loginUser,
                                      @PathVariable("userId") Integer userId,
                                      @RequestBody String body) {
        String oper = "更新本用户信息";
        log.info("====>{}, accountId: {}, body: {}", oper, userId, body);

        // 检查是不是登录本人
        if (userId == null) {
            return Result.error(oper).msg("找不到用户id");
        }
        if (!userId.equals(loginUser.getId())) {
            return Result.error(oper).msg("只能更新自己的账号信息");
        }

        // 更新数据
        User user = JSON.parseObject(body, User.class);
        User data = new User();
        data.setId(user.getId());
        data.setNick(user.getNick());
        data.setPhone(user.getPhone());
        data.setUpdated(LocalDateTime.now());
        userService.updateById(user);
        return Result.success(oper).data("time", data.getUpdated());
    }

    @PatchMapping("/my-pwd")
    public Result updateMyPwd(@AuthenticationPrincipal User loginUser,
                              @RequestBody String body) {
        String oper = "更新本用户密码";
        log.info("====>{}, body: {}", oper, body);

        // 权限校验
        if (loginUser.getId() == null) {
            return Result.error(oper).msg("无法更新密码：找不到用户id");
        }

        JSONObject json = JSON.parseObject(body);
        String pwd = json.getString("pwd");
        if (StringUtils.isBlank(pwd)) {
            return Result.error(oper).msg("无法更新密码：密码不能为空");
        }

        String encodedPwd = passwordEncoder.encode(pwd);
        UpdateWrapper<User> w = new UpdateWrapper<>();
        w.eq("id", loginUser.getId());
        w.set("pwd", encodedPwd);
        userService.update(w);
        return Result.success(oper);
    }





}
